package vn.demand.dragon.model
{
	import mx.collections.XMLListCollection;
	import mx.controls.Alert;
	
	import org.puremvc.as3.interfaces.IProxy;
	import org.puremvc.as3.patterns.proxy.Proxy;
	
	import vn.demand.dragon.FFIAApplicationFacade;
	import vn.demand.dragon.model.business.LoadTaskLogByReferenceDelegate;
	import vn.demand.dragon.model.business.SaveTaskLogDelegate;
	import vn.demand.utils.DpUtils;
	
	public class TaskLogProxy extends Proxy implements IProxy
	{
		public static const NAME:String = "TaskLogProxy";
		
		public var errorStatus:String;
		
		private var tasklogList:XMLListCollection;
		
		public var userProxy:UserProxy = null;
		
		public static function makeId(projectVO:Object):String {
        	return NAME + projectVO.project_id + "::";
        }
		
		public function TaskLogProxy(proxyName:String, data:Object) 
        {
            super (proxyName, data );
            userProxy = facade.retrieveProxy(UserProxy.NAME) as UserProxy;
        }
        
        public function get projectVO():Object {
        	return data as Object;
        }
        
        public function reinit(projectVO:Object):void {
        	this.data = projectVO;
        	tasklogList = new XMLListCollection();
        }
        
        public function get taskProxy():TaskProxy {
        	return facade.retrieveProxy(TaskProxy.makeId(projectVO)) as TaskProxy;
        }
        
        public function get masterdataProxy():MasterdataProxy {
        	return facade.retrieveProxy(MasterdataProxy.NAME) as MasterdataProxy;
        }
        
        public function loadTaskLogByReference():void {
			var delegate:LoadTaskLogByReferenceDelegate = new LoadTaskLogByReferenceDelegate(resultLoadTaskLogByReference, failedLoadTaskLogByReference);
			delegate.loadTaskLogByReferenceService(projectVO.project_id);
		}
		
		public function resultLoadTaskLogByReference(rpcEvent:Object):void {
			tasklogList = new XMLListCollection(rpcEvent.result.task_logs.log);
			sendNotification(FFIAApplicationFacade.LOAD_TASK_LOG_BY_REFERENCE_SUCCESS, projectVO, projectVO.project_id);
		}
		
		public function failedLoadTaskLogByReference(rpcEvent:Object):void {
			errorStatus = "Could not load quotation lines!";
			sendNotification(FFIAApplicationFacade.LOAD_TASK_LOG_BY_REFERENCE_FAILED, errorStatus, projectVO.project_id);
		}
		
		public function get tasklogDP():XMLListCollection {
			return tasklogList;
		}
		
		public function newTaskLog():XML {
			return new XML("<log>" + 
					"<task_log_project>" + projectVO.project_id + "</task_log_project>" + 
					"<task_log_currency>" + masterdataProxy.currencyVND + "</task_log_currency>" + 
					"<task_log_exchange_rate>1</task_log_exchange_rate>" +
					"<task_log_division>" + userProxy.userInfo.div_id + "</task_log_division>" + 
					"<task_log_costcenter>" + userProxy.userInfo.cc_id + "</task_log_costcenter>" + 
					"</log>");
		}
		
		public function removeTaskLog(selIndex:int):Object {
			return tasklogDP.removeItemAt(selIndex);
		}
		
		public function copyTaskLog(projectVO:Object, copyItem:Object, targetRow:int):Object {
			var item:XML = new XML(XML(copyItem).toXMLString());
			item['task_log_project'] = String(projectVO.project_id);
			item['task_log_id'] = '';
			item['task_log_is_complete'] = false;
			item['task_log_completed_date'] = null;
			if (targetRow == tasklogDP.length - 1) {
				tasklogDP.addItemAt(item, targetRow);
			} else {
				tasklogDP.setItemAt(item, targetRow);
			}
			return item;
		}
		
		public function saveTaskLog():void {
			for(var i:int = 0; i < tasklogList.length; i++) {
				var o:Object = tasklogList.getItemAt(i);
				if (o.is_new == true) {
					tasklogList.removeItemAt(i);					
				}
			}
			var xml:String = "<root>" + tasklogList.toXMLString() + "</root>";
			var delegate:SaveTaskLogDelegate = new SaveTaskLogDelegate(resultSaveTaskLog, faultSaveTaskLog);
			delegate.saveTaskLog(xml);
		}
		
		public function resultSaveTaskLog(rcpEvent:Object):void {
			var success:Boolean = rcpEvent.result.success == 'true'; 
			if (success) {
				sendNotification(FFIAApplicationFacade.TASK_LOG_UPDATED, projectVO, projectVO.project_id);
			} else {
				RIALogger.error(this, "Save quotation lines failed with error message: \n" + rcpEvent.result.errors);
				sendNotification(FFIAApplicationFacade.TASK_LOG_UPDATE_FAILED, String(rcpEvent.result.errors));				
			}
		}
		
		public function faultSaveTaskLog(rcpEvent:Object):void {
			Alert.show("" + rcpEvent.fault)
			errorStatus = "Something wrong when save quotation lines!";
			sendNotification(FFIAApplicationFacade.TASK_LOG_UPDATE_FAILED, errorStatus, projectVO.project_id);
		}
		
		public function isTaskLogComplete(itemIndex:int):Boolean {
			var sel:Object = tasklogDP.getItemAt(itemIndex);
			return DpUtils.isTrue(sel.task_log_is_complete);
		}
		
	}
}